package com.iflytek.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//定义一个SpringBoot的拦截器，需要实现HandlerInterceptor接口
public class FirstInterceptor implements HandlerInterceptor {

	//会在请求进入Controller之前执行
	//如果此方法返回true，则请求能进入Controller执行
	//如果此方法返回false，则请求直接结束
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("第一个拦截器，控制器方法调用前处理.......");

		HttpSession session = request.getSession();
		if(session.getAttribute("username") == null){
			response.sendRedirect("/login");  //重定向
			return false;
        }

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("第一个拦截器，控制器方法调用后处理.......");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("第一个拦截器，请求结束后处理.......");
	}
}